#pragma once
#include <memory>
#include <vector>
#include <sys/select.h>
#include <algorithm>
#include "../logsystem/logger/log.h"
#include "Socket.hpp"
using namespace Net_Work;
const int gbacklog = 5;
const int num = sizeof(fd_set) * 8;
class SelectServer
{
public:
    SelectServer(int port) : _port(port), _listensock(new TcpSocket()), _stop(false), fd_nums(num, nullptr)
    {
    }

    void Init()
    {
        // 创建
        _listensock->BuildListenSocketMethod(_port, gbacklog);
        // 初始化
        fd_nums[0] = _listensock.get();
    }

    void Loop()
    {
        while (!_stop)
        {
            // 不能直接监听，把交给select
            fd_set rfds;
            FD_ZERO(&rfds);
            // 将listen添加到集合中
            // FD_SET(_listensock->GetSockfd(), &rfds);
            // select 等待
            // 将fd_nums集合填充进fd_set
            int maxfd = _listensock->GetSockfd();
            for (auto &sock : fd_nums)
            {
                if (sock)
                {
                    maxfd = std::max(maxfd, sock->GetSockfd());
                    FD_SET(sock->GetSockfd(), &rfds);
                }
            }
            struct timeval tv
            {
                5, 0
            };
            // int n = select(_listensock->GetSockfd() + 1, &rfds, nullptr, nullptr, &tv);
            PrintSet();
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, &tv);
            switch (n)
            {
            case 0:
                ILOG("事件未就绪...,last time%u.%u", tv.tv_sec, tv.tv_usec);
                break;
            case -1:
                DLOG("select error");
            default:
                ILOG("事件就绪,last time%u.%u", tv.tv_sec, tv.tv_usec);
                HandlerEvent(rfds);
                break;
            }
            sleep(1);
        }
        _stop = true;
    }

    ~SelectServer()
    {
        _stop = true;
        _listensock->CloseSockFd();
    }

private:
    void HandlerEvent(fd_set &rfds)
    {
        // 遍历rfds
        for (int i = 0; i < num; i++)
        {
            if (fd_nums[i])
            {
                int fd = fd_nums[i]->GetSockfd();

                if (FD_ISSET(fd, &rfds))
                {
                    // 一个连接就绪的可能:1.listen  2.read
                    if (fd == _listensock->GetSockfd())
                    {
                        HandlerAccept();
                    }
                    // 普通sock //简单的读写
                    else
                    {
                        HandlerRead(i);
                    }
                }
            }
        }
    }
    void HandlerAccept()
    {
        ILOG("获取一个新连接!");
        std::string clientip;
        uint16_t clientport;
        Socket *sock = _listensock->AcceptConnection(&clientip, &clientport);
        if (!sock)
        {
            DLOG("获取连接失败!");
            return;
        }
        ILOG("获取连接成功!ip:%s port:%d", clientip.c_str(), clientport);
        // 添加到fd_nums
        int i = 0;
        for (; i < num; i++)
        {
            if (!fd_nums[i])
            {
                fd_nums[i] = sock;
                break;
            }
        }
        // 满了!!
        if (i == num)
        {
            WLOG("accept error!link full!!");
            sock->CloseSockFd();
            delete sock;
        }
    }

    void HandlerRead(int i)
    {
        std::string buffer;
        bool ret = fd_nums[i]->Recv(&buffer, 1024);
        if (ret > 0)
        {
            std::cout << "client say#" << buffer << std::endl;
            // 发回消息
            std::string tmp = "你好client,我是server:" + buffer;
            fd_nums[i]->Send(tmp);
        }
        // 异常或者直接关闭
        else
        {
            ILOG("link break!!! maybe client quit or error");
            // 关闭描述符
            // 将数组的值置为空
            fd_nums[i]->CloseSockFd();
            delete fd_nums[i];
            fd_nums[i] = nullptr;
        }
    }
    void PrintSet()
    {
        std::cout << "fd_nums:";
        for (auto &sock : fd_nums)
        {
            if (sock)
                std::cout << sock->GetSockfd() << " ";
        }
        std::cout << std::endl;
    }

private:
    int _port;
    bool _stop;
    std::vector<Socket *> fd_nums; // 事件先添加进描述符数组
    std::unique_ptr<Socket> _listensock;
};